package com.app.redis;

import com.app.commond.CmdCenterSendELock;
import com.app.commond.entity.CmdLockBean;
import redis.clients.jedis.JedisPubSub;
import soft.common.BConvrtUtil;
import soft.common.BytesHexStrTranslate;
import soft.common.JSONUtil;
import soft.ifs.INetChanel;
import soft.ifs.IWriteLog;
import soft.log.LogWriter;
import soft.net.lconectserver.LConectServer;
import soft.net.lconectserver.ServerConMap;

import java.util.List;


/**
 * @author: taoroot
 * @date: 2017/11/4
 * @description: 订阅者
 */
public class Subscriber extends JedisPubSub {
    private static final IWriteLog log = new LogWriter(Subscriber.class);

    @Override
    public void onMessage(String channel, String message) {
        log.info(channel + " : " + message);
        //订阅锁操作指令
        try {
            if ("oprLock".equals(channel)) {
                CmdLockBean cmdLockBean = JSONUtil.genObject(message, CmdLockBean.class);
                ServerConMap store = LConectServer.store;
                List<INetChanel> iNetChanels = (List) store.getAllChanels();
                if(iNetChanels.size()>=0) {
                    INetChanel chanel = iNetChanels.get(0);
                    byte oprType = (byte) 0x38;
                    if (cmdLockBean.getCmd() == 38) {
                        oprType = (byte) 0x38;
                    } else if (cmdLockBean.getCmd() == 32) {
                        oprType = (byte) 0x32;
                    }
                    if (cmdLockBean.getLockType() == 1) {
                        byte[] key = cmdLockBean.getPassword().getBytes();

                        chanel.sendData(new CmdCenterSendELock(oprType, cmdLockBean.getLockDevID(), key));
                    } else {
                        byte[] key = BytesHexStrTranslate.getPassByte(cmdLockBean.getPassword());
                        chanel.sendData(new CmdCenterSendELock((byte) cmdLockBean.getCmd(), cmdLockBean.getLockDevID(), key));
                    }
                }

            }
        }catch (Exception ex){
            ex.printStackTrace();
        }


    }

    @Override
    public void onSubscribe(String channel, int subscribedChannels) {
        System.out.println(String.format("subscribe redis channel success, channel %s, subscribedChannels %d",
                channel, subscribedChannels));
    }

    @Override
    public void onUnsubscribe(String channel, int subscribedChannels) {
        System.out.println(String.format("unsubscribe redis channel, channel %s, subscribedChannels %d",
                channel, subscribedChannels));

    }

}
